from django import forms
from .models import *

class UserForms(forms.ModelForm):
    class Meta:
        model = UserModels
        fields = ["username", "password"]

    def clean(self):
        username = self.cleaned_data.get("username")
        password = self.cleaned_data.get("password")
        if not UserModels.objects.filter(username=username).exists():
            raise forms.ValidationError("账户不正确")
        if not UserModels.objects.get(username=username).password==password:
            raise forms.ValidationError("密码不正确")

    def get_error(self):
        before_dict = self.errors.get_json_data()
        result_dict = {}
        result_list = []
        for k, v in before_dict.items():
            for i in v:
                result_list.append(i)
            result_dict[k] = result_list
        return result_dict

class RegisterForms(forms.ModelForm):
    password2 = forms.CharField()

    class Meta:
        model = UserModels
        exclude = ["message"]

    def clean(self):
        username = self.cleaned_data.get("username")
        password = self.cleaned_data.get("password")
        password2 = self.cleaned_data.get("password2")
        tel = self.cleaned_data.get("tel")

        if UserModels.objects.filter(username=username).exists():
            raise forms.ValidationError("用户名唯一")
        elif password != password2:
            raise forms.ValidationError("两次密码不一致")
        elif UserModels.objects.filter(tel=tel):
            raise forms.ValidationError("电话唯一")

    def get_error(self):
        before_dict = self.errors.get_json_data()
        result_dict = {}
        result_list = []
        for k, v in before_dict.items():
            for i in v:
                result_list.append(i)
            result_dict[k] = result_list
        return result_dict
